iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
0
自我挑戰組

前端我來了 - 30天 JavaScript 從無到有 系列 第 7

[30天 JavaScript 從無到有 Day 7] Array

  • 分享至 

  • xImage
  •  

宣告的方式

// Initialize new array
var city = ['Taipei', 'Taichung', 'Hualien']; //常用
var sample = new Array('Taipei', false);
console.log(city); // output ['Taipei', 'Taichung', 'Hualien']

常用 function
透過位置取值

console.log(city[1]); // output 'Taichung'

取長度

console.log(city.length); // output 3

換值、取值

city[1] = 'Yilan';
console.log(city); // output ['Taipei', 'Yilan', 'Hualien']
city[4] = 'Taichung';
console.log(city); // output ["Taipei", "Yilan", "Hualien", empty, "Taichung"]
console.log(city.length); // output 5

取位置

console.log(city.indexOf(Taipei)); // output 0
console.log(city.indexOf(apple)); // output -1 (not found this value) -> test

塞入值

// add value (last place) 
sample.push(1);
console.sample(sample); // output ['Taipei', false, 1]

// add value (first place) 
sample.unshift(6);
console.sample(sample); // output [6, 'Taipei', false, 1]

移除值

// remoce value (last place) 
sample.pop();
console.sample(sample); // output [6, 'Taipei', false]

// remoce value (first place) 
sample.shift(6);
console.sample(sample); // output ['Taipei', false, 1]

CODING CHALLENGE 3
題目 : 怕有版權問題稍微調整

/*
Eric went to 3 restaurants. The bills were $220, $86 and $46.

To tip the waiter a fair amount, Eric created a tip calculator function. He likes to tip 18% of the bill when the bill is less than $60, 13% when the bill is between $60 and $180, and 10% if the bill is more than $180.

In the end, Eric would will have 2 arrays:
1) All three tips
2) All three final paid amounts
*/

做答

var bill = [220, 86, 46];
function countTipsPercentage(billAmount){
    var percentage;
    if(billAmount < 60){
        percentage = 0.18;
    }else if(billAmount >= 60 && billAmount < 220){
        percentage = 0.13;
    }else {
        percentage = 0.1;
    }
    return percentage * billAmount
}
var tips = [countTipsPercentage(bill[0]),
            countTipsPercentage(bill[1]),
            countTipsPercentage(bill[2])];
var totalAmount = [bill[0] + tips[0],
                   bill[1] + tips[1],
                   bill[2] + tips[2]];
console.log(tips)
console.log(totalAmount)

小知識 : 0.1 可以直接打.1 ~


新手練功中, 歡迎指教、點評~

課程 : https://www.udemy.com/course/the-complete-javascript-course/


上一篇
[30天 JavaScript 從無到有 Day 6] Function
下一篇
[30天 JavaScript 從無到有 Day 8] Object, Properties and Methods
系列文
前端我來了 - 30天 JavaScript 從無到有 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言